<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {

    /**
     * Authenticates a user.
     * The example implementation makes sure if the username and password
     * are both 'demo'.
     * In practical applications, this should be changed to authenticate
     * against some persistent user identity storage (e.g. database).
     * @return boolean whether authentication succeeds.
     */
    private $_id;
    private $_name;

//    public function decryptIt($q) {
//        $cryptKey = 'MARGUERITE-HOTEL-DL-123654';
//        $qDecoded = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($cryptKey), base64_decode($q), MCRYPT_MODE_CBC, md5(md5($cryptKey))), "\0");
//        return( $qDecoded );
//    }

    public function authenticate() {
        $record = NguoiDung::model()->findByAttributes(array('Email' => $this->username));  // here I use Email as user name which comes from database
//        $pass = decryptIt($this->password);
        if ($record === null) {
            $this->_id = 'user Null';
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        } else if ($record->MatKhau !== $this->password) {            // here I compare db password with passwod field
            //$this->_id = $this->Email;
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
        } else {
            $this->_id = $record['Id'];
            $this->_name = $record['Ten'];
            $this->setState('Email', $record['Email']);
//            if ($record->QUYEN === 'ADMIN') {
//                $this->_name = 'ADMIN';
//                $this->setState('QUYEN', 'ADMIN');
//            } elseif ($record->QUYEN === 'EMPLOYEE') {
//                $this->_name = 'Nhân viên';
//                $this->setState('QUYEN', 'EMPLOYEE');
//            } else {
//                $KH = KhachHang::model()->findByAttributes(array('USER' => $this->username));
//                $this->_name = $KH->TENKH;
//                $this->setState('title', $KH->TENKH);
//            }
            $this->errorCode = self::ERROR_NONE;
        }
        return !$this->errorCode;
    }

    public function getId() {       //  override Id
        return $this->_id;
    }

    public function getName() {     // override Name
        return $this->_name;
    }
    

}
